$(document).ready(function() {
    var new_element = document.createElement("script");
    new_element.setAttribute("type", "text/javascript");
    new_element.setAttribute("src", "js/md5.js");
    document.body.appendChild(new_element);
    $('#login').click(function(event) {
        $("#pass").val( $.md5($('#pass').val()));
        var check = $('#check').prop("checked");
        if (user == "" || pass == "") {
            alertDelay(3, '用户名或密码不允许为空');
            return false;
        }
        $.ajax({
            url: "/News/loginCheck.html",
            type: "POST",
            data: $("#login_form").serialize(),
            async: false,
            dataType: "json",
            cache: false,
            processData: false,
            success: function(data) {
            	if(data.state==200){
                    alertDelay(1, '登录成功');
                    window.location.href = '/News/backManagent.html?user='+$("#user").val();
            	}else if(data.state==101){
            		alertDelay(4, '账号密码错误');
            		 $("#pass").val("");
            		 $("#user").val("");
            	}
            	
            	
            },
            error: function(err) {
                alertDelay(4, '登录失败');
            }
        });
    });
});

function alertDelay(state, message, time) {
    $('#alert').stop();
    if (time == null) {
        time = 1500;
    }
    switch (state) {
        case 1:
            var success = createRandomId();
            $('<div>').appendTo('#alert').attr('id', success).css("width", "100%").addClass('alert alert-success').html(message).show().delay(time).fadeOut(function() {
                $("#" + success).remove();
            });
            break;
        case 2:
            var info = createRandomId();
            $('<div>').appendTo('#alert').attr('id', info).css("width", "100%").addClass('alert alert-info').html(message).show().delay(time).fadeOut(function() {
                $("#" + info).remove();
            });
            break;
        case 3:
            var warning = createRandomId();
            $('<div>').appendTo('#alert').attr('id', warning).css("width", "100%").addClass('alert alert-warning').html(message).show().delay(time).fadeOut(function() {
                $("#" + warning).remove();
            });
            break;
        case 4:
            var danger = createRandomId();
            $('<div>').appendTo('#alert').attr('id', danger).css("width", "100%").addClass('alert alert-danger').html(message).show().delay(time).fadeOut(function() {
                $("#" + danger).remove();
            });
            break;
    }

    function createRandomId() {      
        return (Math.random() * 100).toString(16).substr(0, 4) + '-' + (new Date()).getTime() + '-' + Math.random().toString().substr(2, 5);  
    }
}